
package pd.trabalho.pkg1415;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Server implements Runnable{
    static ServerSocket sckServer;
    MulticastSocket sckMServer;
    static ArrayList <Socket> sckClient;
    ArrayList <Socket> sckRep;
    static Socket mysock, clisock;
    boolean logado=false;
    static int tcpPort;
    static int udpPort;
    DatagramSocket datasock;
    boolean running;

    

    //1. A lista de ficheiros existentes no sistema é gerida apenas pelo servidor
    Server(Socket s) throws IOException{
     
        ServerSocket sckServer = new ServerSocket(6000);
        this.clisock = s;
        logado = false;
        
    }
    
    public void atendeCliente() throws IOException, ClassNotFoundException{
        Object obj;
        
        ObjectInputStream in = new ObjectInputStream(clisock.getInputStream());
        ObjectOutputStream out = new ObjectOutputStream(clisock.getOutputStream());
        Msg msg = new Msg();
        obj = in.readObject();

        if(obj instanceof Msg.login){
            if(validaLogin(obj,clisock)==0){
                logado= true;
                msg.setCmd("Logado");
                out.writeObject(msg);
                out.flush();
            }
            else
            {
                logado = false;
                msg.setCmd("Dados Invalidos");
                out.writeObject(msg);
                out.flush();
            }
        }
    }
         
    
    public static int validaLogin(Object dados, Socket socket) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        Scanner sc = null;
        Msg msg = new Msg();
        Msg.login log = msg.new login();
        log = (Msg.login) dados;
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
        String user, pw;
        try {
            File fich = new File("Users.txt");
            sc = new Scanner(fich);
            while (sc.hasNextLine()) {
                String str = new String(sc.nextLine());
                String[] result = str.split("\\s");
                user = log.getUser();
                pw = log.getPw();
                if(result[0].equals(user) && result[1].equals(pw)){
                    sc.close();
                    return 0;
                }
            }
        }finally{
            sc.close();
        }     
        return 1;
    }
    
    @Override
    public void run(){
        
        try {
            
            
            
            atendeCliente();
            
            
        } catch (IOException ex) {
            System.out.println("ERROR: " + ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    public static void main(String[] args){
        
        Thread t;
        
         if (args.length != 5){
            System.out.println("Sintaxe: <servername> <tcpip> <udpip> <client file> <repository file>");
            return;
        }
        try{
            
            while(true){
            System.out.println("Server started. Waiting for users");
            String servername = args[0];
            tcpPort = Integer.parseInt(args[1]);
            udpPort = Integer.parseInt(args[2]);
            String clifile = args[3];
            String repfile = args[4];
            
            clisock = sckServer.accept();
            
            t = new Thread(new Server(clisock));
            t.start();
            }
        
        }catch(Exception e){
            System.out.println("ERROR: " + e.getMessage());
        }
        
    }
   
}
